package org.jeecg.modules.online.cgform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.online.cgform.entity.OnlCgformField;
import org.jeecg.modules.online.cgform.entity.OnlCgformHead;
import org.jeecg.modules.online.cgform.mapper.OnlCgformFieldMapper;
import org.jeecg.modules.online.cgform.mapper.OnlCgformHeadMapper;
import org.jeecg.modules.online.cgform.service.IOnlineBaseAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("onlineBaseAPI")
public class OnlineBaseAPIServiceImpl implements IOnlineBaseAPI {

    @Autowired
    private OnlCgformHeadMapper onlCgformHeadMapper;
    @Autowired
    private OnlCgformFieldMapper onlCgformFieldMapper;

    @Override
    public String getOnlineErpCode(String code, String tableType) {
        // 只有是子表的时候才会走下面的 逻辑
        if("3".equals(tableType)){
            String tableId = code.substring(1);
            OnlCgformHead head = onlCgformHeadMapper.selectById(tableId);
            if(head!=null && head.getTableType()==3){
                LambdaQueryWrapper<OnlCgformField> queryFields = new LambdaQueryWrapper<OnlCgformField>()
                        .eq(OnlCgformField::getCgformHeadId, tableId);
                List<OnlCgformField> ls = onlCgformFieldMapper.selectList(queryFields);
                if(ls!=null && ls.size()>0){
                    String mainTableName = null;
                    for(OnlCgformField temp: ls){
                        if(StringUtil.isNotEmpty(temp.getMainTable())){
                            mainTableName = temp.getMainTable();
                            break;
                        }
                    }
                    LambdaQueryWrapper<OnlCgformHead> queryTable = new LambdaQueryWrapper<OnlCgformHead>()
                            .eq(OnlCgformHead::getTableName, mainTableName);
                    OnlCgformHead mainTb = onlCgformHeadMapper.selectOne(queryTable);
                    String tableTheme = mainTb.getThemeTemplate();
                    if(mainTb!=null && ("innerTable".equals(tableTheme) || "erp".equals(tableTheme))){
                        code = "/"+mainTb.getId();
                    }
                }
            }
        }
        return code;
    }
}
